package com.example.shiwu.util;

import android.content.SharedPreferences;

import com.chaquo.python.PyObject;
import com.chaquo.python.Python;

import org.json.JSONException;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DataParseBackupsUtil {

    private final static String INDEX_ERR = "err";

    public static Map<String,Object> map;
    public static HashMap<String, Object> mapDouble;
    public static Object ob;
    private static Python py;
    private static PyObject pyobj;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor editor;
    private ArrayList<String> tx_voltage = new ArrayList<String>();//发送电压
    private ArrayList<String> tx_current = new ArrayList<String>();//发射电流
    private ArrayList<String> rx_voltage = new ArrayList<String>();//接受电压
    public static Object DataToParse(String str, Integer header, Integer pulse_indx,
                                     SharedPreferences.Editor editor, SharedPreferences mSharedPreferences) throws JSONException, InterruptedException {
        /**
         *
         */
        String receiveCode = "";
        String strh = "";
        String strh1 = "";
        String count = "";
        String strData ="";
        String strPulse_indx = "";
        String strPulse_count ="";
        Integer strHead = 0;

        //Integer pulse_indx = 0;
        Integer pulse_count = 0;
        Integer indx = 0;
        Integer rec_count = 0;
        Integer packet_lens = 0;
        Integer errorCount = 0;

        if(str.equals("0,Success;")){
            return str;
        } else if (str.equals("0,Bad_Param;")) {
            return str;
        }
        if(str.contains("0,Success;")){
            strh1 = str.replaceAll("0,Success;","");
            strh = strh1.substring(0,strh1.indexOf(","));
            if(str.contains("count")){
                count = str.substring(str.indexOf("count,")+1,str.length());
                System.out.println("--------------count-----------------"+count);
            }
        }
        if(!strh1.equals("")){
            String indexCount = strh1.substring(0,strh1.indexOf(";"));
            String[] strArray = indexCount.split(",");
            strPulse_indx =  strArray[1];
            strPulse_count =  strArray[2];
            packet_lens = Integer.valueOf(DataParseBackupsUtil.initPython(strPulse_count));
            if(packet_lens != 0){
                editor.remove("packet_lens");
                editor.putInt("packet_lens", packet_lens);
                editor.commit();
            }

            strHead = header;
            strData = strh1.replace(indexCount,"").replace(";","").replace(",count=*","").trim();
        }else{
            strHead = header;
            System.out.println("--------------------- strHead-----------------"+strHead);
            strData = str.substring(str.indexOf("Uª"),str.length());
        }

        String[] strLis = null;
        if(strData.contains(",")){
            strLis = strData.split(",");
        }else{
            strLis = new String[]{strData};
        }

        switch (strHead){
            case 0:
                map = new HashMap<String,Object>();
                map.put("kAcknowledge", strLis[0]);
                ob = map;
                break;
            case 1:
                break;
            case 2:
                break;
            case 3:
                map = new HashMap<String,Object>();
                map.put("mode", strLis[0]);
                map.put("frep", strLis[1]);
                map.put("pulse",strLis[2]);
                map.put("txVoltage", strLis[3]);
                ob = map;
                break;
            case 4:
                break;
            case 5:
                break;
            case 6:
                break;
            case 7:
                break;
            case 8:
                break;
            case 9:
                break;
            case 10:
                String jsonpy="";
                try {
                    ///String[] strDataArray = strData.substring(strData.indexOf("U"),strData.length()).split(",");
                    String strData1 = strData.replaceAll("/,","//");
                    //System.out.println("strData1 =============================== "+strData1);
                    String[] strDataArray = strData1.substring(strData1.indexOf("U"),strData1.length()).split(",");
                    //String[] strDataArray = strData.substring(strData.indexOf("U"),strData.length()).split(",");
                    StringBuffer sb = new StringBuffer();

                   // if(pulse_indx == 4){
                        for (int i = 0; i < strDataArray.length; i+=5) {
                            //System.out.println(" i ===================== "+i +" $$ strDataArray= "+strDataArray[i]);
                            //header AA55
                            if(strDataArray[i].equals("Uª")){
                                jsonpy = DecodeUtfStruct(strDataArray[i]);
                                //System.out.println("============ header =========== " + jsonpy);
                            }else {
                                System.out.println(" i ===================== "+i +" $$ header= "+strDataArray[i]);
                                errorCount+= 1;
                            }

                        }
                        for (int i = 1; i < strDataArray.length; i+=5) {// 采样点的编号
                            if(strDataArray[i-1].equals("Uª")){
                                if(strDataArray[i].contains("//")){
                                    strDataArray[i].replace("//","/,");
                                    jsonpy = initPython(strDataArray[i]);
                                    indx =  Integer.parseInt(jsonpy);
                                    //System.out.println("============ indx =========== " + indx );
                                }else{
                                    //System.out.println("============ indx1 =========== " + strDataArray[i]+" i+1 = "+strDataArray[i-1]);
                                    jsonpy = initPython(strDataArray[i]);
                                    if(!jsonpy.equals("err")){

                                        indx =  Integer.parseInt(jsonpy);
                                        //System.out.println("============ indx2 =========== " + indx);
                                    }

                                }
                            }else {
                                System.out.println(" i ===================== "+i +" $$ 采样点的编号= "+strDataArray[i]);
                                errorCount+= 1;
                            }

                        }
                        for (int i = 2; i < strDataArray.length; i+=5) { //tx_voltage
                            if(strDataArray[i-2].equals("Uª")) {
                                if (strDataArray[i].contains("//")) {
                                    strDataArray[i].replace("//", "/,");
                                    jsonpy = DecodeTxVStruct(strDataArray[i], indx);
                                    //System.out.println("============ TX_V = " + jsonpy);
                                    if(!"".equals(jsonpy) && !jsonpy.equals("null")){
                                        sb.append(jsonpy+",");
                                    }
                                    else if("null".equals(jsonpy)) {
                                        errorCount+= 1;
                                    }
                                } else {
                                    jsonpy = DecodeTxVStruct(strDataArray[i], indx);
                                   // System.out.println("============ TX_V = " + jsonpy);
                                    if(!"".equals(jsonpy) && !jsonpy.equals("null")){
                                        sb.append(jsonpy+",");
                                    }
                                    else if("null".equals(jsonpy)) {
                                        errorCount+= 1;
                                    }
                                }
                            }else {
                                System.out.println(" i ===================== "+i +" $$ tx_voltage= "+strDataArray[i]);
                                errorCount+= 1;
                            }

                        }
                        for (int i = 3; i < strDataArray.length; i+=5) { //tx_current
                            if(strDataArray[i-3].equals("Uª")) {
                                if(i == 3){
                                    sb.append(";");
                                }
                                if (strDataArray[i].contains("//")) {
                                    strDataArray[i].replace("//", "/,");
                                    jsonpy = DecodeTxCStruct(strDataArray[i], indx);
                                    //System.out.println("============ tx_c = " + jsonpy);
                                    if("".equals(jsonpy) && !jsonpy.equals("null")){
                                        sb.append(jsonpy+",");
                                    }
                                    else if("null".equals(jsonpy)) {
                                        errorCount+= 1;
                                    }
                                } else {
                                    jsonpy = DecodeTxCStruct(strDataArray[i], indx);
                                   // System.out.println("============ tx_c = " + jsonpy);
                                    if(!"".equals(jsonpy) && !jsonpy.equals("null")){
                                        sb.append(jsonpy+",");
                                    }
                                    else if("null".equals(jsonpy)) {
                                        errorCount+= 1;
                                    }
                                }
                            }else {
                                System.out.println(" i ===================== "+i +" $$ tx_current= "+strDataArray[i]);
                                errorCount+= 1;
                            }
                        }
                        for (int i = 4; i < strDataArray.length; i+=5) { //rx_voltage
                            if(strDataArray[i-4].equals("Uª")) {
                                if(i == 4){
                                    sb.append(";");
                                }
                                if (strDataArray[i].contains("//")) {
                                    strDataArray[i].replace("//", "/,");
                                    jsonpy = DecodeRxVStruct(strDataArray[i],indx);
                                    //System.out.println("============ rx_v = " + jsonpy);
                                    if(!"".equals(jsonpy) && !jsonpy.equals("null")){
                                        sb.append(jsonpy+",");
                                    }
                                    else if("null".equals(jsonpy)) {
                                        errorCount+= 1;
                                    }
                                }else{
                                    jsonpy = DecodeRxVStruct(strDataArray[i], indx);
                                   // System.out.println("============ rx_v = " + jsonpy);
                                    if(!"".equals(jsonpy) && !jsonpy.equals("null")){
                                        sb.append(jsonpy+",");
                                    }
                                    else if("null".equals(jsonpy)) {
                                        errorCount+= 1;
                                    }
                                }
                                Integer header_count =mSharedPreferences.getInt("header_count", 0);
                                packet_lens =mSharedPreferences.getInt("packet_lens", 0);
                                //System.out.println("---packet_lens_new= "+packet_lens);

                                header_count +=1;
                                //System.out.println("============ header_count =========== " + header_count);
                                rec_count = header_count;
                                packet_lens -= 3;
                                System.out.println("------packet_lens= "+packet_lens);
                                editor.remove("header_count");
                                editor.putInt("header_count", header_count);
                                editor.remove("packet_lens");
                                editor.putInt("packet_lens", packet_lens);
                                editor.commit();
                            }else {
                                System.out.println(" i ===================== "+i +" $$ rx_voltage= "+strDataArray[i]);
                                errorCount+= 1;
                            }
                        }


                    editor.remove("packet_lens");
                    editor.putInt("packet_lens", packet_lens);
                    editor.commit();
                    System.out.println("---packet_lens == rec_count--- "+packet_lens +" -- "+rec_count);
                    mapDouble = new HashMap<String,Object>();
                    Integer bak_packet_lens =mSharedPreferences.getInt("bak_packet_lens", 0);
                    if(packet_lens <= 0){
                        if (bak_packet_lens.equals(rec_count)){
                            mapDouble.put("correct", "1");
                            mapDouble.put("data", sb);
                            //mapDouble.put("id", strh);
                            mapDouble.put("error_count", errorCount);
                            ob = mapDouble;
                        }
                    }
                    mapDouble.put("error_count", errorCount);
                    ob = mapDouble;


                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                break;
            case 11:
                break;
            case 12:
                break;
            case 13:
                break;
            case 14:
                break;
            case 15:
                break;
            case 16:
                break;
            case 17:
                break;
            case 18://获取设备的firmware版本
                ob = strLis[0];
                break;

        }
        return ob;

    }
    public static Object DataToParseNoHeader(String str) throws JSONException {

        String strh = "";
        String strData = "";
        Integer indx = 0;
        String jsonpy = "";
        Integer dataCount = 0;
        Integer errorCount = 0;
        try {
            String strData1 = str.replaceAll("/,", "//");

            String[] strDataArray = strData1.split(",");
            //System.out.println("strData2 =============================== " + strData1);
            StringBuffer sb = new StringBuffer();


            for (int a = 0; a < strDataArray.length; a += 3) { //tx_voltage

                    if (strDataArray[a].contains("//")) {
                        strDataArray[a].replace("//", "/,");
                        jsonpy = DecodeTxVStruct(strDataArray[a], indx);
                        //System.out.println("============ TX_V = " + jsonpy);
                        if ("".equals(jsonpy) && !jsonpy.equals("null")) {
                            sb.append(jsonpy + ",");
                            dataCount += 1;
                        }
                        else {
                            dataCount += 1;
                            errorCount+= 1;
                        }
                    } else {
                        jsonpy = DecodeTxVStruct(strDataArray[a], indx);
                        // System.out.println("============ TX_V = " + jsonpy);
                        if ("".equals(jsonpy) && !jsonpy.equals("null")) {
                            sb.append(jsonpy + ",");
                            dataCount += 1;
                        }
                        else if("null".equals(jsonpy)) {
                            dataCount += 1;
                            errorCount+= 1;
                        }
                    }


            }
            for (int b = 1; b < strDataArray.length; b += 3) { //tx_current

                    if (b == 3) {
                        sb.append(";");
                    }
                    if (strDataArray[b].contains("//")) {
                        strDataArray[b].replace("//", "/,");
                        jsonpy = DecodeTxCStruct(strDataArray[b], indx);
                        //System.out.println("============ tx_c = " + jsonpy);
                        if ("".equals(jsonpy) && !jsonpy.equals("null")) {
                            sb.append(jsonpy + ",");
                            dataCount += 1;
                        }
                        else if("null".equals(jsonpy)) {
                            dataCount += 1;
                            errorCount+= 1;
                        }
                    } else {
                        jsonpy = DecodeTxCStruct(strDataArray[b], indx);
                        // System.out.println("============ tx_c = " + jsonpy);
                        if ("".equals(jsonpy) && !jsonpy.equals("null")) {
                            sb.append(jsonpy + ",");
                            dataCount += 1;
                        }
                        else if("null".equals(jsonpy)) {
                            dataCount += 1;
                            errorCount+= 1;
                        }
                    }

            }
            for (int c = 2; c < strDataArray.length; c += 3) { //rx_voltage
                    if (c == 4) {
                        sb.append(";");
                    }
                    if (strDataArray[c].contains("//")) {
                        strDataArray[c].replace("//", "/,");
                        jsonpy = DecodeRxVStruct(strDataArray[c], indx);
                        //System.out.println("============ rx_v = " + jsonpy);
                        if ("".equals(jsonpy) && !jsonpy.equals("null")) {
                            sb.append(jsonpy + ",");
                            dataCount += 1;
                        }
                        else if("null".equals(jsonpy)) {
                            dataCount += 1;
                            errorCount+= 1;
                        }
                    } else {
                        jsonpy = DecodeRxVStruct(strDataArray[c], indx);
                        // System.out.println("============ rx_v = " + jsonpy);
                        if ("".equals(jsonpy) && !jsonpy.equals("null")) {
                            sb.append(jsonpy + ",");
                            dataCount += 1;
                        }
                        else if("null".equals(jsonpy)) {
                            dataCount += 1;
                            errorCount+= 1;
                        }
                    }

            }
            mapDouble = new HashMap<String, Object>();
            mapDouble.put("data", sb);
            mapDouble.put("id", strh);
            mapDouble.put("header_count", dataCount);
            mapDouble.put("error_count", errorCount);
            ob = mapDouble;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return ob;

    }

    /**
     * 拼接多帧数据组成不包含id,pulse_indx,pulse的数据 比如 AA55,。。。。。
     * @return
     */


    public static String getDataForHeaderIndex(String str){
        String strh,strh1,count;
        String strPulse_indx = "";
        String strPulse_count = "";
        int strHead = 100;
        if(str.contains("0,Success;")){
            strh1 = str.replaceAll("0,Success;","");
            if(strh1.length()>0){
                strh = strh1.substring(0,strh1.indexOf(","));
                if(str.contains("count")){
                    count = str.substring(str.indexOf("count,")+1,str.length());
                    System.out.println("--------------count-----------------"+count);
                }
                if(strh.length()>0){
                    String[] strArray = strh1.substring(0,strh1.indexOf(";")).split(",");
                    strPulse_indx =  strArray[1];
                    strPulse_count =  strArray[2];
                    strHead = Integer.valueOf(strh);
                }

            }
            String headIndx = strHead+","+strPulse_indx+","+strPulse_count;
        }
        return strHead+","+strPulse_indx+","+strPulse_count;
    }
    public static int bytesToInt(byte[] a){
        int ans=0;
        for(int i=0;i<4;i++){
            ans<<=8;//左移 8 位
            ans|=a[3-i];//保存 byte 值到 ans 的最低 8 位上
            intPrint(ans);
        }
        return ans;
    }
    public static void intPrint(int a){//将 int 按位从左到右打印
        int count=0;
        for(int i=31;i>=0;i--){
            System.out.print((a>>i)&1);
            count++;
            if(count==4){//每四位为一组，用空格分开
                System.out.print(" ");
                count=0;
            }
        }
        System.out.println();
    }

    //Object转Map
    public static Map<String, Object> getObjectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> cla = obj.getClass();
        Field[] fields = cla.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String keyName = field.getName();
            Object value = field.get(obj);
            if (value == null)
                value = "";
            map.put(keyName, value);
        }
        return map;
    }

    private static void initPy(){
        py = Python.getInstance();
        pyobj = py.getModule("Struct_Data");
    }
    public static String initPython(String val) throws JSONException, InterruptedException {
        initPy();
        String data ="";
        if(!pyobj.callAttr("DecodeStruct", val).equals("null")){
            data = String.valueOf(pyobj.callAttr("DecodeStruct", val).toJava(int.class));
        }else{
            return INDEX_ERR;
        }

        //System.out.println("-=-=-=-=-=-=-=-=-=-==- initPython_data ="+data);
        return data;
    }
    public static String bytesPython(String val) throws JSONException, InterruptedException {
//        py = Python.getInstance();
//        pyobj = py.getModule("Struct_Data");
        initPy();
        String data = "";
        if(!pyobj.callAttr("DecodeByteStruct", val).toString().equals("")){
            data = Arrays.toString(pyobj.callAttr("DecodeByteStruct", val).toJava(Integer[].class));
        }
        System.out.println("-=-=-=-=-=-=-=-=-=-==- DecodeByteStruct_data ="+data);
        return data;
    }
    public static String DecodeIntStruct(String val) throws JSONException, InterruptedException {
//        py = Python.getInstance();
//        pyobj = py.getModule("Struct_Data");
        initPy();
        String data = "";
        if(!pyobj.callAttr("DecodeIntStruct", val).toString().equals("") && !pyobj.callAttr("DecodeIntStruct", val).toString().equals("null")){
            data = String.valueOf(pyobj.callAttr("DecodeIntStruct", val).toJava(double.class));
        }else {//处理垃圾数据 发送 kConfirm 0
            if (pyobj.callAttr("DecodeIntStruct", val).toString().equals("null")) {
                data = "";
            }else {
                return INDEX_ERR;
            }

        }
        //System.out.println("-=-=-=-=-=-=-=-=-=-==- DecodeIntStruct_data ="+data);
        return data;
    }
    public static String DecodeUtfStruct(String val) throws JSONException, InterruptedException {
//        py = Python.getInstance();
//        pyobj = py.getModule("Struct_Data");
        initPy();
        String data = String.valueOf(pyobj.callAttr("DecodeUtfStruct", val).toJava(String.class));
        //System.out.println("-=-=-=-=-=-=-=-=-=-==- DecodeUtfStruct_data ="+data);
        return data;
    }
    public static String DecodeTxVStruct(String val,Integer indx) throws JSONException, InterruptedException {
        initPy();
        String data = "";
        if(!pyobj.callAttr("DecodeTxVStruct", val,indx).toString().equals("") && !pyobj.callAttr("DecodeTxVStruct", val,indx).toString().equals("null")){
            data = String.valueOf(pyobj.callAttr("DecodeTxVStruct", val,indx).toJava(float.class));
        }else {//处理垃圾数据 发送 kConfirm 0
            if (pyobj.callAttr("DecodeTxVStruct", val,indx).toString().equals("null")) {
                data = "";
            }else {
                return INDEX_ERR;
            }

        }
        //System.out.println("-=-=-=-=-=-=-=-=-=-==- DecodeTxVStruct_data ="+data);
        return data;
    }

    public static String DecodeTxCStruct(String val,Integer indx) throws JSONException, InterruptedException {
        initPy();
        String data = "";
        if(!pyobj.callAttr("DecodeTxCStruct", val,indx).toString().equals("") && !pyobj.callAttr("DecodeTxCStruct", val,indx).toString().equals("null")){
            data = String.valueOf(pyobj.callAttr("DecodeTxCStruct", val,indx).toJava(float.class));
        }else {//处理垃圾数据 发送 kConfirm 0
            if (pyobj.callAttr("DecodeTxCStruct", val,indx).toString().equals("null")) {
                data = "";
            }else {
                return INDEX_ERR;
            }

        }
        //System.out.println("-=-=-=-=-=-=-=-=-=-==- DecodeTxCStruct_data ="+data);
        return data;
    }

    public static String DecodeRxVStruct(String val,Integer indx) throws JSONException, InterruptedException {
        initPy();
        String data = "";
        if(!pyobj.callAttr("DecodeRxVStruct", val,indx).toString().equals("") && !pyobj.callAttr("DecodeRxVStruct", val,indx).toString().equals("null")){
            data = String.valueOf(pyobj.callAttr("DecodeRxVStruct", val,indx).toJava(double.class));
        }else {//处理垃圾数据 发送 kConfirm 0
            if (pyobj.callAttr("DecodeRxVStruct", val,indx).toString().equals("null")) {
                data = "";
            }else {
                return INDEX_ERR;
            }

        }
        //System.out.println("-=-=-=-=-=-=-=-=-=-==- DecodeRxVStruct_data ="+data);
        return data;
    }

    public static int getUint16(int i){
        return i & 0x0000ffff;
    }
    public static List<Double> byteArrayToDoubleList(byte[] bytes){
        List<Double> d = new ArrayList<>(bytes.length/16);
        byte[] doubleBuffer = new byte[8];
        for(int j = 0; j < bytes.length; j += 8) {
            System.arraycopy(bytes, j, doubleBuffer, 0, doubleBuffer.length);
            d.add(getFloat64(doubleBuffer));
        }
        return d;
    }
    public static double getFloat64(byte[] bytes)
    {
        return Double.longBitsToDouble(((bytes[0] & 0xFFL) << 56)
                | ((bytes[1] & 0xFFL) << 48)
                | ((bytes[2] & 0xFFL) << 40)
                | ((bytes[3] & 0xFFL) << 32)
                | ((bytes[4] & 0xFFL) << 24)
                | ((bytes[5] & 0xFFL) << 16)
                | ((bytes[6] & 0xFFL) << 8)
                | ((bytes[7] & 0xFFL) << 0));
    }
    /**
     * 将byte类型的arr转换成float
     * @return
     */
    public static List<Float> byteArrayToFloatList(byte[] bytes){
        List<Float> d = new ArrayList<>(bytes.length/8);
        byte[] doubleBuffer = new byte[4];
        for(int j = 0; j < bytes.length; j += 4) {
            System.arraycopy(bytes, j, doubleBuffer, 0, doubleBuffer.length);
            d.add(bytes2Float(doubleBuffer));
        }
        return d;
    }
    /**
     * 将byte数组数据转换成float
     * @param arr
     * @return
     */
    public static float bytes2Float(byte[] arr) {
        int accum = 0;
        accum = accum|(arr[0] & 0xff) << 0;
        accum = accum|(arr[1] & 0xff) << 8;
        accum = accum|(arr[2] & 0xff) << 16;
        accum = accum|(arr[3] & 0xff) << 24;
        return Float.intBitsToFloat(accum);
    }

    // 从byte数组的index处的连续4个字节获得一个float
    public static float getFloat(byte[] arr, int index) {
        return Float.intBitsToFloat(getInt(arr, index));
    }
    // 从byte数组的index处的连续4个字节获得一个int
    public static int getInt(byte[] arr, int index) {
        return 	(0xff000000 	& (arr[index+0] << 24))  |
                (0x00ff0000 	& (arr[index+1] << 16))  |
                (0x0000ff00 	& (arr[index+2] << 8))   |
                (0x000000ff 	&  arr[index+3]);
    }
}
